package com.link2room.ironhide.service.impl;

import com.link2room.common.dao.ICommonDao;
import com.link2room.common.jpa.criteria.CriteriaUtil;
import com.link2room.common.jpa.result.QueryResult;
import com.link2room.common.util.ClassConverUtil;
import com.link2room.ironhide.dto.result.base.PositionBaseDto;
import com.link2room.ironhide.entity.L2RGroupPositionBase;
import com.link2room.ironhide.service.IL2RGroupPositionBaseService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by sss on 2016/10/12.
 */
@Service("l2RGroupPositionBaseService")
public class L2RGoupPositionBaseServiceImpl implements IL2RGroupPositionBaseService {
    @Resource
    ICommonDao commonDao;

    @Override
    public List<PositionBaseDto> listGroupPositionBase(String lhotelGroupCode, Long cityCode)throws Exception{
        L2RGroupPositionBase querypb=new L2RGroupPositionBase();
        querypb.setLhotelGroupCode(lhotelGroupCode);
        querypb.setCityCode(cityCode);
        QueryResult<L2RGroupPositionBase> positionBaseResult = commonDao.findAll(L2RGroupPositionBase.class, CriteriaUtil.getCriteriaAllEQ(querypb), null, null, null, null);
        QueryResult<PositionBaseDto> positionBaseDtoResult= ClassConverUtil.copyQueryResultToDtoQueryResult(positionBaseResult,PositionBaseDto.class, false);
        List<PositionBaseDto> positionBaseList = positionBaseDtoResult.getResultlist();
        List<PositionBaseDto> topList=new ArrayList<>();
        List<PositionBaseDto> tempList=new ArrayList<>();

        for(PositionBaseDto positionBase:positionBaseList){
            if("ROOT".equals(positionBase.getPositionType())){
                //取出顶级节点
                topList.add(positionBase);
            }else {
                //保存字节点
                tempList.add(positionBase);
            }
        }
        for(PositionBaseDto top:topList){
            List<PositionBaseDto> childList=childNodeList(tempList,top.getPositionCode());
            top.setChildren(childList);
        }
        return topList;
    }

    public List<PositionBaseDto> childNodeList(List<PositionBaseDto> inList, String parentCode)throws Exception{
        List<PositionBaseDto> mainList=new ArrayList<>();
        List<PositionBaseDto> tempList=new ArrayList<>();

        for(PositionBaseDto in:inList){
            if(parentCode.equals(in.getPositionType())&&!"市辖区".equals(in.getName())){
                mainList.add(in);
            }else {
                tempList.add(in);
            }
        }

        for(PositionBaseDto main:mainList){
            List<PositionBaseDto> childList=childNodeList(tempList,main.getPositionCode());
            main.setChildren(childList);
        }
        return mainList;
    }
}
